package main

import (
	"context"
	"encoding/json"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"

	"go.mongodb.org/mongo-driver/mongo/options"

	"go.mongodb.org/mongo-driver/mongo"
)

// FindByUid uid过滤条件
type FindByUid struct {
	Uid uint64 `bson:"uid"` // uid赋值为1
}

func main() {
	// 1. 建立连接
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://10.0.0.11:27017"))
	if err != nil {
		panic(err)
	}
	defer func() {
		if err := client.Disconnect(context.TODO()); err != nil {
			panic(err)
		}
	}()

	// 2. 选择数据库、选择表
	coll := client.Database("my_db").Collection("today")

	// 3. 查询
	var result bson.M
	var uid uint64 = 1
	err = coll.FindOne(context.TODO(), bson.D{{"uid", uid}}).Decode(&result)
	if err == mongo.ErrNoDocuments {
		fmt.Printf("No document was found with the uid %d\n", uid)
		return
	}
	if err != nil {
		panic(err)
	}

	jsonData, err := json.MarshalIndent(result, "", "    ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", jsonData)
}
